import { useState, useEffect } from 'react';
import {
    Form, Input, Select, DatePicker, Button, Table,
    Space, Modal, message, Tabs, Image, Upload, Radio
} from 'antd';
import {
    SearchOutlined, ReloadOutlined, EditOutlined,
    DeleteOutlined, PlusOutlined, UploadOutlined
} from '@ant-design/icons';
import { dataList, dataDel, dataAdd, imageFile, classList } from '@/api/teacher';
import './module.css/module.teacher.css';
import dayjs, { Dayjs } from 'dayjs';
import {path} from '@/config/index';


// 类型定义
interface TeacherRecord {
    id: number | string;
    nickname: string;
    username: string;
    title?: string;
    age?: number;
    gender?: '1' | '2';
    intr?: string;
    avatar?: string;
    birthday?: string;
    squad_id?: number | string;
}

interface ClassItem {
    id: number | string;
    title?: string;
    name?: string;
}

interface PaginationParams {
    current: number;
    pageSize: number;
    total: number;
}

interface AuditCounts {
    '1': number;
    '2': number;
    '3': number;
}

interface AddFormValues {
    phone: string;
    password?: string;
    classId: number | string;
    position: string;
    name: string;
    gender: '1' | '2';
    birthDate?: Dayjs;
}

interface SearchFormValues {
    teacherName?: string;
    teacherPhone?: string;
    className?: string;
    gender?: '1' | '2';
    birthDate?: Dayjs;
    position?: string;
}

const { Option } = Select;
const { TabPane } = Tabs;

const Teacher: React.FC = () => {
    // 表单实例
    const [form] = Form.useForm<SearchFormValues>();
    const [addForm] = Form.useForm<AddFormValues>();

    // 状态管理
    const [loading, setLoading] = useState<boolean>(false);
    const [data, setData] = useState<TeacherRecord[]>([]);
    const [classData, setClassData] = useState<ClassItem[]>([]);
    const [activeTab, setActiveTab] = useState<string>('3');
    const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([]);
    const [pagination, setPagination] = useState<PaginationParams>({
        current: 1,
        pageSize: 100,
        total: 0,
    });
    const [auditCounts, setAuditCounts] = useState<AuditCounts>({
        '1': 0,
        '2': 0,
        '3': 0
    });
    const [isAddModalVisible, setIsAddModalVisible] = useState<boolean>(false);
    const [uploading, setUploading] = useState<boolean>(false);
    const [imageUrl, setImageUrl] = useState<string>('');
    const [ageError, setAgeError] = useState<string>('');
    const [currentEditId, setCurrentEditId] = useState<number | string | null>(null);
    const [isEdit, setIsEdit] = useState<boolean>(false);

    // 数据获取相关方法
    const fetchClassList = async () => {
        try {
            const response = await classList({ squad_id_: '', role: 1 });
            if (response.code === 1) {
                setClassData(response.data.list || []);
            } else {
                message.error(response.msg || '获取班级列表失败');
            }
        } catch (error) {
            console.error('获取班级列表失败:', error);
            message.error('获取班级列表失败');
        }
    };

    const fetchTeacherList = async (params = {}, pageParams: { current: number; pageSize: number }) => {
        setLoading(true);
        try {
            const response = await dataList({
                current: pageParams.current,
                pageSize: pageParams.pageSize,
                audits: activeTab,
                ...params,
            });

            if (response.code === 1) {
                setData(response.data.list || []);
                setPagination(prev => ({
                    ...prev,
                    current: pageParams.current,
                    pageSize: pageParams.pageSize,
                    total: response.data.list.length || 0,
                }));

                setAuditCounts(prev => ({
                    ...prev,
                    [activeTab]: response.data.list.length || 0
                }));
            } else {
                message.error(response.msg || '获取数据失败');
            }
        } catch (error) {
            console.error('获取教师列表失败:', error);
            message.error('获取教师列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 初始化加载
    useEffect(() => {
        fetchTeacherList({}, {
            current: 1,
            pageSize: pagination.pageSize,
        });
        fetchClassList();
    }, [activeTab]);

    // 搜索和重置方法
    const handleSearch = () => {
        form.validateFields().then((values) => {
            const params: Record<string, any> = {};

            if (values.teacherName) params.nickname = values.teacherName;
            if (values.teacherPhone) params.username = values.teacherPhone;
            if (values.className) params.title = values.className;
            if (values.gender) params.gender = values.gender;
            if (values.birthDate) params.birthday = values.birthDate.format('YYYY-MM-DD');
            if (values.position) params.intr = values.position;

            const newPageParams = { current: 1, pageSize: pagination.pageSize };
            fetchTeacherList(params, newPageParams);
            setPagination(prev => ({ ...prev, ...newPageParams }));
            setSelectedRowKeys([]);
        });
    };

    const handleReset = () => {
        form.resetFields();
        const newPageParams = { current: 1, pageSize: pagination.pageSize };
        fetchTeacherList({}, newPageParams);
        setPagination(prev => ({ ...prev, ...newPageParams }));
        setSelectedRowKeys([]);
    };

    // 增删改相关方法
    const handleDelete = (record: TeacherRecord) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除教师 "${record.nickname}" 吗？`,
            onOk: async () => {
                try {
                    const response = await dataDel({ ids: record.id });
                    if (response.code === 1) {
                        message.success('删除成功');
                        fetchTeacherList({}, {
                            current: pagination.current,
                            pageSize: pagination.pageSize,
                        });
                    } else {
                        message.error(response.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    message.error('删除失败');
                }
            },
        });
    };

    const handleBatchDelete = () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的教师');
            return;
        }

        Modal.confirm({
            title: '确认批量删除',
            content: `确定要删除选中的 ${selectedRowKeys.length} 位教师吗？`,
            onOk: async () => {
                try {
                    const idsStr = selectedRowKeys.join(',');
                    const response = await dataDel({ ids: idsStr });
                    if (response.code === 1) {
                        message.success('批量删除成功');
                        // setSelectedRowKeys([]);
                        fetchTeacherList({}, {
                            current: pagination.current,
                            pageSize: pagination.pageSize,
                        });
                    } else {
                        message.error(response.msg || '批量删除失败');
                    }
                } catch (error) {
                    console.error('批量删除失败:', error);
                    message.error('批量删除失败');
                }
            },
        });
    };

    const handleBatchImport = () => {
        message.info('该功能正在开发中');
    };

    const handleAdd = () => {
        setIsAddModalVisible(true);
        setIsEdit(false);
        setCurrentEditId(null);
        setAgeError('');
        setImageUrl('');
        addForm.resetFields();
    };

    // 表单验证相关方法
    const validateAge = (birthDate: Date): boolean => {
        const today = new Date();
        let age = today.getFullYear() - birthDate.getFullYear();
        const monthDiff = today.getMonth() - birthDate.getMonth();

        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }

        return age >= 20;
    };

    const handleDateChange = (date?: Dayjs) => {
        if (date) {
            const isValidAge = validateAge(date.toDate());
            setAgeError(isValidAge ? '' : '年龄必须已满20周岁以上');
        } else {
            setAgeError('');
        }
    };

    const handleEdit = (record: TeacherRecord) => {
        setIsAddModalVisible(true);
        setIsEdit(true);
        setAgeError('');
        setCurrentEditId(record.id);

        // 清除密码字段的校验状态和错误提示
        addForm.setFieldsValue({ password: undefined });
        addForm.validateFields(['password']).catch(() => { });

        // 处理出生日期为dayjs对象，用于DatePicker回显
        let birthDateValue: Dayjs | undefined = undefined;
        if (record.birthday) {
            try {
                birthDateValue = dayjs(record.birthday);
            } catch (error) {
                console.error('日期解析错误:', error);
                const dateStr = record.birthday.replace(/\//g, '-');
                birthDateValue = dayjs(dateStr);
            }
        }

        // 查找班级ID对应的班级对象
        const classItem = classData.find(item => item.id === record.squad_id);

        // 表单回显数据，不包含密码字段
        addForm.setFieldsValue({
            phone: record.username || '',
            name: record.nickname || '',
            gender: record.gender as '1' | '2' || '',
            position: record.intr || '',
            classId: classItem ? classItem.id : '',
            birthDate: birthDateValue
        });

        // 回显图片
        if (record.avatar) {
            setImageUrl(record.avatar.startsWith('http') ? record.avatar : path + record.avatar);
        } else {
            setImageUrl('');
        }
    };

    const handleAddSubmit = async () => {
        try {
            // 编辑模式下，单独验证除密码外的字段
            const fieldsToValidate = isEdit
                ? ['phone', 'name', 'gender', 'position', 'classId', 'birthDate']
                : undefined;

            const values = await addForm.validateFields(fieldsToValidate);

            // 验证年龄
            if (values.birthDate) {
                const isValidAge = validateAge(values.birthDate.toDate());
                if (!isValidAge) {
                    message.error('年龄必须已满20周岁以上');
                    return;
                }
            }

            // 准备提交数据
            const submitData: Record<string, any> = {
                username: values.phone,
                nickname: values.name,
                avatar: imageUrl,
                birthday: values.birthDate ? values.birthDate.format('YYYY-MM-DD') : '',
                gender: values.gender,
                intr: values.position,
                squad_id: values.classId,
                password: values.password || undefined // 编辑时密码可选
            };

            // 编辑操作，添加id
            if (isEdit && currentEditId) {
                submitData.id = currentEditId;
            }

            const response = await dataAdd(submitData);

            if (response.code === 1) {
                message.success(isEdit ? '编辑教师成功' : '添加教师成功');
                setIsAddModalVisible(false);
                addForm.resetFields();
                setImageUrl('');
                setAgeError('');
                setIsEdit(false);
                setCurrentEditId(null);
                // 刷新列表
                fetchTeacherList({}, {
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                });
            } else {
                message.error(response.msg || (isEdit ? '编辑教师失败' : '添加教师失败'));
            }
        } catch (error) {
            console.error('表单验证失败:', error);
        }
    };

    // 图片上传方法
    const handleUpload = async (file: File) => {
        setUploading(true);
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await imageFile(formData);
            if (response.code === 1) {
                setImageUrl(response.data.url);
                message.success('上传成功');
            } else {
                message.error(response.msg || '上传失败');
            }
        } catch (error) {
            console.error('上传失败:', error);
            message.error('上传失败');
        } finally {
            setUploading(false);
        }

        return false; // 阻止默认上传行为
    };

    // 表格相关方法
    const handleTableChange = (newPagination: PaginationParams) => {
        setPagination(prev => ({
            ...prev,
            current: newPagination.current,
            pageSize: newPagination.pageSize,
        }));
        fetchTeacherList({}, {
            current: newPagination.current,
            pageSize: newPagination.pageSize,
        });
    };

    const onSelectChange = (newSelectedRowKeys: (string | number)[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const handleTabChange = (key: string) => {
        if (key === '1' || key === '2') {
            message.info('该功能正在开发中');
            return;
        }
        setActiveTab(key);
        const newPageParams = { current: 1, pageSize: pagination.pageSize };
        setPagination(prev => ({ ...prev, ...newPageParams }));
        fetchTeacherList({}, newPageParams);
    };

    // 表格配置
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    const genderMap = {
        '1': '男',
        '2': '女',
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 60,
            render: (_, __, index) => index + 1 + (pagination.current - 1) * pagination.pageSize,
        },
        {
            title: '姓名',
            dataIndex: 'nickname',
            key: 'nickname',
            align: 'center',
        },
        {
            title: '电话',
            dataIndex: 'username',
            key: 'username',
            align: 'center',
        },
        {
            title: '班级',
            dataIndex: 'title',
            key: 'title',
            align: 'center',
            render: (title) => title || '-',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            align: 'center',
            render: (age) => age || '-',
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            align: 'center',
            render: (gender) => genderMap[gender as keyof typeof genderMap] || '-',
        },
        {
            title: '任职',
            dataIndex: 'intr',
            key: 'intr',
            align: 'center',
            render: (intr) => intr || '-',
        },
        {
            title: '教师图片',
            dataIndex: 'avatar',
            key: 'avatar',
            align: 'center',
            render: (avatar) => avatar ? (
                <Image
                    width={40}
                    height={40}
                    src={avatar}
                    style={{ objectFit: 'cover', borderRadius: '4px' }}
                    placeholder={
                        <div style={{
                            width: 40,
                            height: 40,
                            borderRadius: '4px',
                            background: '#f0f0f0',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}>
                            暂无
                        </div>
                    }
                />
            ) : (
                <div style={{
                    width: 40,
                    height: 40,
                    borderRadius: '4px',
                    background: '#f0f0f0',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '12px'
                }}>
                    暂无
                </div>
            ),
        },
        {
            title: '操作',
            align: 'center',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                        style={{ padding: '0 4px', border: '1px solid #1890ff' }}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record)}
                        style={{ padding: '0 4px', border: '1px solid #ff4d4f' }}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    // 计算20年前的日期
    const twentyYearsAgo = new Date();
    twentyYearsAgo.setFullYear(twentyYearsAgo.getFullYear() - 20);

    // 渲染UI
    return (
        <div>
            <div className='white' style={{ padding: '20px' }}>
                {/* 标题区域 */}
                <div className='teacher'>教师管理</div>

                {/* 搜索区域 */}
                <div className='search'>
                    <Form
                        form={form}
                        layout="horizontal"
                        colon={false}
                        style={{ width: '85%' }}
                    >
                        {/* 第一行 */}
                        <div className='searchList'>
                            <Form.Item name="teacherName" label="教师姓名">
                                <Input placeholder="请输入教师姓名" style={{ width: '225px' }} />
                            </Form.Item>
                            <Form.Item name="teacherPhone" label="教师电话">
                                <Input placeholder="请输入教师电话" style={{ width: '225px' }} />
                            </Form.Item>
                            <Form.Item name="className" label="班级名称">
                                <Input placeholder="请输入班级名称" style={{ width: '225px' }} />
                            </Form.Item>
                        </div>

                        {/* 第二行 */}
                        <div className='searchList'>
                            <Form.Item name="gender" label="性别">
                                <Select placeholder="请选择性别" style={{ width: '225px', marginLeft: '28px' }}>
                                    <Option value="1">男</Option>
                                    <Option value="2">女</Option>
                                </Select>
                            </Form.Item>
                            <Form.Item name="birthDate" label="出生日期">
                                <DatePicker placeholder="请选择出生日期" style={{ width: '225px' }} />
                            </Form.Item>
                            <Form.Item name="position" label="任职">
                                <Input placeholder="请输入任职" style={{ width: '225px', marginLeft: '28px' }} />
                            </Form.Item>
                        </div>
                    </Form>

                    {/* 竖线分割 */}
                    <div style={{ height: '100px', width: '1px', background: '#999999' }}></div>

                    {/* 按钮区域 */}
                    <div className='button'>
                        <Button
                            type="primary"
                            onClick={handleSearch}
                            style={{ width: '100px', background: '#165DFF' }}
                            icon={<SearchOutlined />}
                        >
                            查询
                        </Button>
                        <Button
                            onClick={handleReset}
                            style={{ width: '100px' }}
                            icon={<ReloadOutlined />}
                        >
                            重置
                        </Button>
                    </div>
                </div>

                {/* 选项卡 */}
                <Tabs
                    activeKey={activeTab}
                    onChange={handleTabChange}
                    style={{ marginBottom: '16px', marginTop: '20px' }}
                >
                    <TabPane tab={`已审核(${auditCounts['3']})`} key="3" />
                    <TabPane tab={`待审核(${auditCounts['1']})`} key="1" />
                    <TabPane tab={`已驳回(${auditCounts['2']})`} key="2" />
                </Tabs>

                {/* 操作按钮区域 */}
                <div className='buttonBox'>
                    <div className='refresh'>
                        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                            新建
                        </Button>
                        <Button
                            icon={<DeleteOutlined />}
                            danger
                            onClick={handleBatchDelete}
                            disabled={selectedRowKeys.length === 0}
                        >
                            批量删除
                        </Button>
                        <Button icon={<UploadOutlined />} onClick={handleBatchImport}>
                            批量导入
                        </Button>
                    </div>
                    <div>
                        <img src="./refresh.png" alt="refresh" onClick={handleReset} className='w20' />
                    </div>
                </div>

                <span style={{ marginLeft: 'auto', lineHeight: '32px' }}>
                    {selectedRowKeys.length > 0 ? `已选择 ${selectedRowKeys.length} 项` : ''}
                </span>

                {/* 表格区域 */}
                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        total: pagination.total,
                        showSizeChanger: true,
                        size: 'middle',
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条记录`,
                        pageSizeOptions: ['10', '20', '50', '100'],
                        showSizeChangerTooltip: false,
                    }}
                    onChange={handleTableChange}
                    rowSelection={rowSelection}
                    scroll={{ x: 1000 }}
                />

                {/* 新增/编辑教师模态框 */}
                <Modal
                    title={isEdit ? "编辑教师" : "新建教师"}
                    open={isAddModalVisible}
                    onCancel={() => {
                        setIsAddModalVisible(false);
                        setAgeError('');
                        setIsEdit(false);
                        setCurrentEditId(null);
                    }}
                    footer={[
                        <Button key="cancel" onClick={() => {
                            setIsAddModalVisible(false);
                            setAgeError('');
                            setIsEdit(false);
                            setCurrentEditId(null);
                        }}>
                            取消
                        </Button>,
                        <Button
                            key="submit"
                            type="primary"
                            loading={uploading}
                            onClick={handleAddSubmit}
                        >
                            确定
                        </Button>,
                    ]}
                    width={600}
                >
                    <Form
                        form={addForm}
                        layout="horizontal"
                        style={{ marginTop: '20px' }}
                    >
                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="手机号"
                                name="phone"
                                className='margin14'
                                rules={[
                                    { required: true, message: '请输入手机号' },
                                    {
                                        pattern: /^1[3-9]\d{9}$/,
                                        message: '请输入有效的手机号（11位数字，以1开头）'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入手机号" maxLength={11} />
                            </Form.Item>
                        </div>

                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="密码"
                                name="password"
                                className={isEdit ? 'margin28 edit-mode-password' : 'margin28'}
                                // 编辑模式下完全移除校验规则
                                rules={isEdit ? [] : [
                                    { required: true, message: '请输入密码' },
                                    { min: 6, message: '密码长度不能少于6位' }
                                ]}
                            >
                                <Input.Password
                                    placeholder={isEdit ? "如需修改密码请填写（留空则不修改）" : "请输入密码（不少于6位）"}
                                    allowClear={isEdit}
                                />
                            </Form.Item>
                        </div>

                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="班级"
                                name="classId"
                                className='margin28'
                                rules={[{ required: true, message: '请选择班级' }]}
                            >
                                <Select placeholder="请选择班级">
                                    {classData.map((classItem) => (
                                        <Option key={classItem.id} value={classItem.id}>
                                            {classItem.title || classItem.name}
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </div>
                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="任职"
                                name="position"
                                className='margin28'
                                rules={[{ required: true, message: '请选择任职' }]}
                            >
                                <Select placeholder="请选择任职">
                                    <Option value="语文老师">语文老师</Option>
                                    <Option value="数学老师">数学老师</Option>
                                    <Option value="英语老师">英语老师</Option>
                                    <Option value="化学老师">化学老师</Option>
                                    <Option value="物理老师">物理老师</Option>
                                    <Option value="班主任">班主任</Option>
                                </Select>
                            </Form.Item>
                        </div>

                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="姓名"
                                name="name"
                                className='margin28'
                                rules={[{ required: true, message: '请输入姓名' }]}
                            >
                                <Input placeholder="请输入姓名" />
                            </Form.Item>
                        </div>
                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="性别"
                                name="gender"
                                className='margin28'
                                rules={[{ required: true, message: '请选择性别' }]}
                            >
                                <Radio.Group>
                                    <Radio value="1">男</Radio>
                                    <Radio value="2">女</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </div>

                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="照片"
                                className='margin28'
                                required={true}
                            >
                                <Upload
                                    beforeUpload={handleUpload}
                                    showUploadList={false}
                                    accept="image/*"
                                    listType="picture-card"
                                >
                                    {imageUrl ? (
                                        <div style={{ position: 'relative' }}>
                                            <img
                                                src={imageUrl.startsWith('http') ? imageUrl : path + imageUrl}
                                                alt="avatar"
                                                style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                                            />
                                            <div style={{
                                                position: 'absolute',
                                                top: 0,
                                                right: 0,
                                                background: 'rgba(0,0,0,0.5)',
                                                color: 'white',
                                                padding: '2px 5px',
                                                fontSize: '12px'
                                            }}>
                                                重新上传
                                            </div>
                                        </div>
                                    ) : (
                                        <div style={{ padding: '8px' }}>
                                            <UploadOutlined style={{ fontSize: '20px' }} />
                                            <div style={{ marginTop: '8px' }}>上传照片</div>
                                        </div>
                                    )}
                                </Upload>
                            </Form.Item>
                        </div>
                        <div style={{ width: '90%', margin: 'auto' }}>
                            <Form.Item
                                label="出生日期"
                                name="birthDate"
                                required
                                rules={[{
                                    required: true,
                                    message: '请选择出生日期'
                                }]}
                            >
                                <DatePicker
                                    style={{ width: '100%' }}
                                    placeholder="请选择出生日期"
                                    onChange={handleDateChange}
                                    defaultPickerValue={dayjs('2005-9-1')}
                                    disabledDate={(current) => {
                                        return current && current > dayjs(twentyYearsAgo);
                                    }}
                                />
                            </Form.Item>
                            {ageError && <div style={{ color: 'red' }}>{ageError}</div>}
                            {!ageError && <div style={{ color: 'red' }}>年龄必须已满20周岁以上</div>}
                        </div>
                    </Form>
                </Modal>
            </div>
        </div>
    );
};

export default Teacher;
